package response

import "github.com/gin-gonic/gin"

const (
	CODE_SUCCESS        string = "0000"
	CODE_SYSTEM_FAIL    string = "0001"
	CODE_AUTH_FAIL      string = "0002"
	CODE_BUSINESS_FAIL  string = "0003"
	CODE_VAlIDATED_FAIL string = "0004"
	CODE_SERVER_FAIL    string = "0005"
)

var MsgIdMap map[string]string = map[string]string{CODE_SUCCESS: "SUCCESS", CODE_SYSTEM_FAIL: "服务器发生异常",
	CODE_AUTH_FAIL: "身份效验不通过", CODE_BUSINESS_FAIL: "业务效验不通过", CODE_VAlIDATED_FAIL: "参数效验不通过",
	CODE_SERVER_FAIL: "service fail"}

type Response struct {
	//必须的大写开头
	Code ResCode     `json:"code"` //
	Bo   interface{} `json:"bo"` //返回的业务数据
}

type RedisResponse struct {
	Status     string `json:"status"`
	RedisHosts string `json:"redisHosts"`
}

type ResCode struct {
	Code         string `json:"code"` //消息编码，请求成功："0000" ,服务器发生异常："0001" ，身份效验不通过："0002" ，业务效验不通过："0003" ，参数效验不通过："0004" ， 服务程序发生异常："0005"
	Msg          string `json:"msg"` //消息说明
	ErrDetailMsg string `json:"errDetailMsg"` //存储http调用失败返回的详细信息,包括url和body参数
	MsgId        string `json:"msgId"` //请求成功："Success" ,服务器发生异常："SystemFailed" ，身份效验不通过："AuthFailed" ，业务效验不通过："BusinessFailed" ，参数效验不通过："ValidatedFailed" ， 服务程序发生异常："ServerFailed"
}

func CreateSuccessResCode() ResCode {
	return ResCode{Code: CODE_SUCCESS, MsgId: MsgIdMap[CODE_SUCCESS], Msg: "请求操作成功"}
}

func CreateFailResCode(msg string) ResCode {
	return ResCode{Code: CODE_SERVER_FAIL, Msg: msg, MsgId: MsgIdMap[CODE_SERVER_FAIL]}
}

func CreateFailResCodeWithErrDetailMsg(msg string, errDetailMsg string) ResCode {
	return ResCode{Code: CODE_SERVER_FAIL, Msg: msg, MsgId: MsgIdMap[CODE_SERVER_FAIL], ErrDetailMsg: errDetailMsg}
}

func CreateValidateFailResCode(msg string) ResCode {
	return ResCode{Code: CODE_VAlIDATED_FAIL, Msg: msg, MsgId: MsgIdMap[CODE_VAlIDATED_FAIL]}
}

func GinRecover(context *gin.Context) {
	v := recover()
	if v != nil {
		context.JSON(200, Response{Code: CreateFailResCode(v.(string))})
	}
}

func GinPanic(context *gin.Context, err error) {
	if err != nil {
		context.JSON(200, Response{Code: CreateFailResCode(err.Error())})
		panic(nil)
	}
}

func GinSucess(context *gin.Context, resp interface{}) {
	context.JSON(200, Response{Code: CreateSuccessResCode(), Bo: resp})
}

func GinResponse(context *gin.Context, resp interface{}, err error) {
	GinPanic(context, err)
	GinSucess(context, resp)
}
